package com.fengba.nanzhi.tabbar04.wz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fengba.nanzhi.fengba.MainActivity;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ParentUserActivity extends AppCompatActivity {

    private TextView mPrentPhone;
    private TextView mPrentUserName;
    private TextView mPrentWeChat;
    private ImageView mPrentHeadImg;
    private ImageView mPrentWeChatewm;
    private Button mBtnPrentWechatImg;
    private TextView mTop;
    private ImageButton tjrfh;
    private String parent_user_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wz_activity_parent);

        mPrentPhone = findViewById(R.id.prentphone);
        mPrentUserName = findViewById(R.id.tjruesrname);
        mPrentWeChat = findViewById(R.id.prentwechat);
        mPrentHeadImg = findViewById(R.id.prenttx);
        mPrentWeChatewm = findViewById(R.id.prentwechatewm);
        mBtnPrentWechatImg  = findViewById(R.id.prentbcwechatimg);
        tjrfh =  findViewById(R.id.tjrfh);

        tjrfh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTop = findViewById(R.id.tjrtop);
        ViewGroup.LayoutParams para = mTop.getLayoutParams();
        int top = getStatusBarHeight(ParentUserActivity.this);
        para.height = top;
        mTop.setLayoutParams(para);
        getUser_id();

        OKManager.getInstance().type1026(parent_user_id, new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                try {
                    if(jsonObject.get("message").toString().trim().equals("用户未登录")){
                        Intent intent = new Intent(ParentUserActivity.this,Login.class);
                        startActivity(intent);
                    }else if(jsonObject.get("code").toString().trim().equals("-1")){
                        showToast(ParentUserActivity.this,jsonObject.get("message").toString());
                        finish();
                    }else{
                        JSONObject jsonObject1 = (JSONObject) jsonObject.get("data");
                        mPrentPhone.setText(jsonObject1.get("account").toString());
                        mPrentUserName.setText(jsonObject1.get("realname").toString());
                        mPrentWeChat.setTag(jsonObject1.get("wechat").toString());
                        Glide.with(ParentUserActivity.this).load(jsonObject1.get("headimg").toString()).into(mPrentHeadImg);
                        Glide.with(ParentUserActivity.this).load(jsonObject1.get("wechat_qr_code").toString()).into(mPrentWeChatewm);

                        mBtnPrentWechatImg.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                saveImage(mPrentWeChatewm);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                showToast(ParentUserActivity.this,string);
            }
        });
    }

    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    //保存文件到指定路径
//    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
//        // 首先保存图片
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
//        File appDir = new File(storePath);
//        if (!appDir.exists()) {
//            appDir.mkdir();
//        }
//        String fileName = System.currentTimeMillis() + ".jpg";
//        File file = new File(appDir, fileName);
//        try {
//            FileOutputStream fos = new FileOutputStream(file);
//            //通过io流的方式来压缩保存图片
//            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
//            fos.flush();
//            fos.close();
//
//            //把文件插入到系统图库
//            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//
//            //保存图片后发送广播通知更新数据库
//            Uri uri = Uri.fromFile(file);
//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
//            if (isSuccess) {
//                return true;
//            } else {
//                return false;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
    private void saveImage(ImageView imageView){
        imageView.setDrawingCacheEnabled(true);//开启catch，开启之后才能获取ImageView中的bitmap
        Bitmap bitmap = imageView.getDrawingCache();//获取imageview中的图像
        MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "这是title", "这是description");
        Toast.makeText(ParentUserActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
        imageView.setDrawingCacheEnabled(false);//关闭catch

    }

    private int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public void getUser_id(){
        Object user_info = Preferences.getParam(ParentUserActivity.this,"user_info","");
        try {
            JSONObject myJson = new JSONObject(user_info.toString());

            //账号
            parent_user_id = myJson.get("parent_user_id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
